<template>
  <div class="app-container page-container right-side-dialog">
    <div class="content_view">
      <el-row>
        <el-col :span="6" class="tree_view" :style="{minHeight: height + 'px'}">
          <el-tree
          :data="dept_tree_data"
          default-expand-all
          @node-click="getTableData"
          :expand-on-click-node="false">
          <span class="custom-tree-node" slot-scope="{node, data }">
            <img v-if="node.level === 1" src="../../../assets/images/dept_tree_1.png" alt="" width="15px">
            <img v-if="!node.isLeaf && node.level != 1" src="../../../assets/images/dept_tree_2.png" alt="" width="15px">
            <img v-if="node.isLeaf" src="../../../assets/images/dept_tree_3.png" alt="" width="15px">
            <span style="font-size:14px;">{{ data.dept_name }}</span>
          </span>
        </el-tree>
        </el-col>
        <el-col :span="18" class="table_view" :style="{minHeight: height + 'px'}">
          <div class="main-header">
            <el-row :gutter="20">
              <el-col :span="10" class="left">当前部门：{{select_dept_data.dept_name}}</el-col>
              <el-col :span="14" class="right">
                <span v-if="auth.save != -1" class="spp-btn spp-btn-primary" @click="roleEditVisible = true">新增</span>
              </el-col>
            </el-row>
          </div>
          <el-table ref="table" :data="role_list_data" :height="height-80" size="mini" stripe>
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column label="部门名称" prop="dept_name" min-width="150" align="left" />
            <el-table-column label="角色名称" prop="role_name" min-width="150" align="left" />
            <el-table-column label="角色排序" prop="role_order" min-width="100" align="left" />
            <el-table-column label="角色描述" prop="role_desc" min-width="200" align="left" />
            <el-table-column label="创建时间" min-width="200" align="left">
              <template slot-scope="scope">
                <div>{{ scope.row.create_time ? formatDateTime(scope.row.create_time) : '--' }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="150" fixed="right" align="left">
              <template slot-scope="scope">
                <el-button v-if="auth.update != -1" type="text" @click="roleUpdate(scope.row)">修改</el-button>
                <el-button type="text">
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      更多<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-if="auth.menu != -1" @click.native="getMenuTreeData(scope.row.role_id)">菜单管理</el-dropdown-item>
                      <el-dropdown-item v-if="auth.perm != -1" @click.native="setRolePerm(scope.row.role_id)">权限管理</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <!-- 新增编辑角色 -->
    <el-dialog :title="role_edit_form.title" :append-to-body="true" :visible.sync="roleEditVisible" width="720px" :close-on-click-modal="false">
      <el-form ref="role_edit_form" label-width="0" :model="role_edit_form">
        <div style="margin-left: 5px;" v-if="role_edit_form.type === 'add'">所属部门 {{select_dept_data.dept_name}}</div>
        <div style="margin-left: 5px;" v-if="role_edit_form.type === 'edit'">所属部门 {{role_edit_form.dept_name}}</div>
        <el-form-item prop="role_name">
          <div class="form_lable">角色名称</div>
          <el-input v-model="role_edit_form.role_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item rop="role_order">
          <div class="form_lable">角色排序</div>
          <el-input v-model="role_edit_form.role_order" type="number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="role_desc">
          <div class="form_lable">角色描述</div>
          <el-input v-model="role_edit_form.role_desc" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <span class="spp-btn" @click="roleEditVisible = false">取消</span>
        <span class="spp-btn spp-btn-primary" @click="roleEditSubmit()">保存</span>
      </span>
    </el-dialog>
    <!-- 菜单管理 -->
    <el-dialog title="菜单管理" :visible.sync="roleMenuEditVisible" :close-on-click-modal="false" width="720px">
      <el-scrollbar wrap-class="vertical_scrollbar" :style="{height: height + 'px'}">
        <el-row>
          <el-col :span="8" v-for="(item, key) in role_menu_tree_data.tree" :key="key">
            <el-tree ref="menu_tree" :data="item" :props="defaultProps" show-checkbox node-key="menu_id" default-expand-all :default-checked-keys="role_menu_tree_data.select_menu"></el-tree>
          </el-col>
        </el-row>
      </el-scrollbar>
      <div class="dialog-btn" style="text-align: right">
        <span class="spp-btn" @click="roleMenuEditVisible = false">取消</span>
        <span class="spp-btn spp-btn-primary" @click="roleMenuEditSubmit()">保存</span>
      </div>
    </el-dialog>
    <!-- 权限管理 -->
    <el-dialog title="权限管理" :visible.sync="rolePermEditVisible" :close-on-click-modal="false" width="720px">
      <el-scrollbar wrap-class="vertical_scrollbar" :style="{height: height + 'px'}">
        <el-form ref="role_perm_search_form" :model="role_perm_search_form" :inline="true" label-width="0">
          <div class="form-area">
            <el-form-item label="">
              <el-select v-model="role_perm_search_form.app_id_ex" clearable placeholder="请选择应用id">
                <el-option v-for="item in app_look_dic" :key="item.app_id" :label="item.app_name" :value="item.app_id" />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="role_perm_search_form.perm_name" placeholder="请输入权限名称" />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="role_perm_search_form.perm_desc" placeholder="请输入权限描述" />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="role_perm_search_form.action_key" placeholder="请输入权限路由" />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="role_perm_search_form.controller" placeholder="请输入所属控制器" />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="role_perm_search_form.controller_name" placeholder="请输入控制器名称" />
            </el-form-item>
            <span class="spp-btn spp-btn-primary" @click="getPermTreeData()">搜索</span>
          </div>
        </el-form>
        <div v-for="(item, key) in role_perm_table_data" :key="key">
          <h3>{{item.controller_name}}</h3>
          <el-table ref="perm_table" :data="item.list">
            <el-table-column label="权限路由" prop="action_key" />
            <el-table-column label="权限名称" prop="perm_name" />
            <el-table-column label="" width="100">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.switch" @change="rolePremEditSubmit(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>
<script>
import { tree, roleList, save, update, menuTree, saveMenu, permTree, savePerm, delPerm } from '@/api/pajx/sys/role'
import { app_look } from '@/api/public'
import { formatDateTime } from '@/utils/index'
import { mapState } from 'vuex'
export default {
  name: 'SysRole',
  components: { },
  data() {
    return {
      height: window.innerHeight - 100,
      auth: {},
      app_look_dic: [],
      dept_tree_data: [],
      select_dept_data: {},
      role_list_data: [],
      roleEditVisible: false,
      role_edit_form: {
        title: '新增角色',
        type: 'add',
        dept_name: '',
        dept_code: '',
        role_name: '',
        role_order: '',
        role_desc: ''
      },
      roleMenuEditVisible: false,
      role_menu_tree_data: {
        tree: [],
        select_menu: []
      },
      defaultProps: {
        children: 'children',
        label: 'menu_name'
      },
      select_role_id: '',
      rolePermEditVisible: false,
      role_perm_table_data: [],
      role_perm_search_form: {
        role_id: '',
        app_id_ex: '',
        perm_name: '',
        perm_desc: '',
        action_key: '',
        controller: '',
        controller_name: ''
      }
    }
  },
  computed: {
    ...mapState({
      permission: state => state.permission.permission
    })
  },
  watch: {
    roleEditVisible(val) {
      if (val) {
        this.role_edit_form.title = this.role_edit_form.type==='add'?'新增角色':'编辑角色'
      }
      if (!val) {
        this.role_edit_form.dept_code = ''
        this.role_edit_form.role_name = ''
        this.role_edit_form.role_order = ''
        this.role_edit_form.role_desc = ''
        this.role_edit_form.type = 'add'
      }
    }
  },
  methods: {
    formatDateTime: formatDateTime,
    // 获取按钮权限
    permissionAuth() {
      this.auth.save = this.permission.indexOf('/api/sys/role/save')
      this.auth.update = this.permission.indexOf('/api/sys/role/update')
      this.auth.menu = this.permission.indexOf('/api/sys/role/menu/tree')
      // this.auth.perm = this.permission.indexOf('/api/sys/role/perm/tree')
    },
    // 获取应用id字典
    getAppLookDic() {
      app_look().then(response => {
        this.app_look_dic = response.data
      })
    },
    // 获取部门树
    getDeptTree() {
      tree().then(response => {
        this.dept_tree_data = this.formatTree(response.data, null)
        this.select_dept_data = this.dept_tree_data[0]
        this.getTableData(this.select_dept_data)
      })
    },
    formatTree(data, parentId) {
      var that = this
      var itemArr = [];
      data.forEach(function( val, index ) {
        if(val.dept_pcode === parentId){
          var newNode = {
            dept_code: val.dept_code,
            dept_id: val.dept_id,
            dept_name: val.dept_name,
            dept_pcode: val.dept_pcode,
            dept_pname: val.dept_pname,
            status_flag: val.status_flag,
            children: that.formatTree(data, val.dept_code)
          };
          if(newNode.children.length == 0){
            delete newNode.children;
          }
          itemArr.push(newNode); 
        }
      })
      return itemArr
    },
    // 点击树状图获取表格数据
    getTableData(data) {
      this.select_dept_data = data
      this.getRoleListData()
    },
    // 获取角色列表
    getRoleListData() {
      roleList(this.select_dept_data).then(response => {
        this.role_list_data = response.data
      })
    },
    // 新增编辑角色
    roleEditSubmit() {
      // 新增
      if (this.role_edit_form.type === 'add') {
        this.role_edit_form.dept_code = this.select_dept_data.dept_code
        save(this.role_edit_form).then(response => {
          this.roleEditVisible = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getRoleListData()
        })
      }
      // 修改
      if (this.role_edit_form.type === 'edit') {
        update(this.role_edit_form).then(response => {
          this.roleEditVisible = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getRoleListData()
        })
      }
    },
    // 修改回显
    roleUpdate(data) {
      this.roleEditVisible = true
      this.role_edit_form.dept_name = data.dept_name
      this.role_edit_form.dept_code = data.dept_code
      this.role_edit_form.role_name = data.role_name
      this.role_edit_form.role_order = data.role_order
      this.role_edit_form.role_desc = data.role_desc
      this.role_edit_form.role_id = data.role_id
      this.role_edit_form.type = 'edit'
    },
    // 角色菜单管理
    getMenuTreeData(role_id) {
      this.select_role_id = role_id
      menuTree(this.select_role_id).then(response => {
        this.roleMenuEditVisible = true
        var data = response.data
        var tree_data = []
        data.forEach(function( val, index ) {
          tree_data.push([val])
        })
        this.role_menu_tree_data.tree = tree_data
        this.role_menu_tree_data.select_menu = this.getSelectMenu(data, [])
      })
    },
    // 获取默认选中菜单
    getSelectMenu(data, select_menu) {
      var that = this
      data.forEach(function( val, index ) {
        if(val.menu_level){
          if(val.role_id && val.children.length === 0){
            select_menu.push(val.menu_id)
          }
          that.getSelectMenu(val.children, select_menu)
        }
      })
      return select_menu
    },
    // 编辑角色菜单
    roleMenuEditSubmit() {
      var menu_tree_list = this.$refs.menu_tree
      var menu_ids = []
      menu_tree_list.forEach(function( val, index ) {
        menu_ids = menu_ids.concat(val.getCheckedKeys())
        menu_ids = menu_ids.concat(val.getHalfCheckedKeys())
      })
      var form = {
        role_id: this.select_role_id,
        menu_ids: menu_ids.join(',')
      }
      saveMenu(form).then(response => {
        this.getMenuTreeData(this.select_role_id)
      })
    },
    // 权限管理
    setRolePerm(role_id) {
      this.select_role_id = role_id
      this.rolePermEditVisible = true
      this.getPermTreeData()
    },
    getPermTreeData() {
      this.role_perm_search_form.role_id = this.select_role_id
      permTree(this.role_perm_search_form).then(response => {
        response.data.forEach(function( val) {
          var list = val.list
          list.forEach(function( ev) {
            if(ev.role_id){
              ev.switch = true
            } else {
              ev.switch = false
            }
          })
        })
        this.role_perm_table_data = response.data
      })
    },
    // 编辑角色权限
    rolePremEditSubmit(data){
      var form = {
        role_id: this.select_role_id,
        perm_id: data.perm_id
      }
      if(data.switch) {
        savePerm(form).then(response => {})
      }else{
        delPerm(form).then(response => {})
      }
    }
  },
  created() {
    this.permissionAuth()
    this.getAppLookDic()
    this.getDeptTree()
  }
}
</script>
<style lang="scss">
.tree_view{
  border-right: 1px solid #E1E3E6;
  background: #F5F7FA;
  padding-top: 16px;
  .el-tree{
    background: #F5F7FA;
  }
}
.table_view{
  padding-left: 16px;
  .main-header{
    padding: 10px 0;
  }
}
</style>
